<?php
class Topic
{
	private $db;

	public function __construct($db)
	{
		$this->db = $db;
	}

	//	获取最新讨论
	public function getLatestTopics($limit = 15)
	{
		try {
			$limit = max(1, (int) $limit);
			$limit = min($limit, 50); // 设置上限防止过大查询

			$stmt = $this->db->prepare("
                SELECT
                    t.*,
                    u.username,
                    u.avatar_url
                FROM
                    topics t
                JOIN
                    users u ON t.user_id = u.id
                ORDER BY
                    t.created_at DESC
                LIMIT :limit
            ");

			$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
			$stmt->execute();

			return $stmt->fetchAll(PDO::FETCH_ASSOC);

		} catch (PDOException $e) {
			error_log("Database error in Topic model: " . $e->getMessage());
			throw new Exception("Failed to retrieve topics");
		}
	}

	// 获取指定分类下的讨论
	public function getTopicsByCategory($categoryId)
	{
		try {
			$stmt = $this->db->prepare("
            SELECT
                t.*,
                u.username,
                u.avatar_url
            FROM
                topics t
            JOIN
                users u ON t.user_id = u.id
            WHERE
                t.category_id = :category_id
            ORDER BY
                t.created_at DESC
        ");

			$stmt->bindValue(':category_id', $categoryId, PDO::PARAM_INT);
			$stmt->execute();

			return $stmt->fetchAll(PDO::FETCH_ASSOC);

		} catch (PDOException $e) {
			error_log("Database error in Topic model: " . $e->getMessage());
			throw new Exception("Failed to retrieve topics by category");
		}
	}

	// 发帖
	public function insertTopic($userId, $categoryId, $title, $content, $isPinned = 0, $isClosed = 0)
	{
		$query = "INSERT INTO topics
					 (user_id, category_id, title, content, is_pinned, is_closed)
					 VALUES
					 (:user_id, :category_id, :title, :content, :is_pinned, :is_closed)";

		$stmt = $this->db->prepare($query);
		$stmt->bindParam(':user_id', $userId, PDO::PARAM_INT);
		$stmt->bindParam(':category_id', $categoryId, PDO::PARAM_INT);
		$stmt->bindParam(':title', $title, PDO::PARAM_STR);
		$stmt->bindParam(':content', $content, PDO::PARAM_STR);
		$stmt->bindParam(':is_pinned', $isPinned, PDO::PARAM_INT);
		$stmt->bindParam(':is_closed', $isClosed, PDO::PARAM_INT);
		$stmt->execute();

		return $this->db->lastInsertId();
	}

	// 获取指定id下的帖子
	public function getTopicById($topicId)
	{
		$query = "SELECT * FROM topics WHERE topic_id = :topic_id";

		$stmt = $this->db->prepare($query);
		$stmt->bindParam(':topic_id', $topicId, PDO::PARAM_INT);
		$stmt->execute();

		return $stmt->fetch(PDO::FETCH_ASSOC);
	}
}
?>